﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace zaklad_rtv
{
    public class SelectedIndexToIsEnabledConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (int)value >= 0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException("Cannot convert from IsEnabled to SelectedIndex");
        }
    }

    public class CostLongToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var num = (long)value;
            return CostConverter.NumberToText(num);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var str = (string)value;
            return CostConverter.TextToNumber(str);
        }
    }

    public class EndServiceDateToStringConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var date = (DateTime)value;
            return date.Equals(DateTime.MaxValue) ? "" : date.ToString(StringConstants.DateFormat);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var stringDate = (string)value;
            return string.IsNullOrEmpty(stringDate) ? DateTime.MaxValue : DateTime.Parse(stringDate);
        }
    }

    public class CostConverter
    {
        public static long TextToNumber(string text)
        {
            if (string.IsNullOrEmpty(text.Trim()))
            {
                return 0L;
            }
            long result;
            var costString = text.Replace(',', '.');
            if (costString.Contains("."))
            {
                var digitsAfterDot = costString.Substring(costString.IndexOf('.') + 1).Length;
                if (digitsAfterDot == 1) costString += "0";
                costString = costString.Replace(".", "");
                result = long.Parse(costString);
            }
            else
            {
                result = long.Parse(costString) * 100;
            }
            return result;
        }

        public static string NumberToText(long number)
        {
            var result = number.ToString(CultureInfo.InvariantCulture);
            var missingZeroCount = 3 - result.Length;
            for (var i = 0; i < missingZeroCount; i++)
            {
                result = result.Insert(0, "0");
            }
            return result.Insert(result.Length - 2, ",");
        }
    }
}
